const db = require('../config/database');
const si = require('systeminformation');
const logger = require('../config/logger');
const redisClient = require('../config/redis');
const ftpServer = require('../services/ftpServer');

/**
 * 获取系统概览统计
 */
exports.getOverview = async (req, res) => {
  try {
    // 文件总体积
    const [fileSizeResult] = await db.query(
      'SELECT SUM(file_size) as total_size, COUNT(*) as total_files FROM files WHERE is_deleted = 0 AND is_directory = 0'
    );

    // 在线用户数
    const [onlineUsersResult] = await db.query(
      'SELECT COUNT(*) as count FROM users WHERE is_online = 1'
    );

    // 今日上传下载统计
    const [todayStats] = await db.query(
      `SELECT
        SUM(CASE WHEN type = 'upload' AND status = 'completed' THEN file_size ELSE 0 END) as today_upload,
        SUM(CASE WHEN type = 'download' AND status = 'completed' THEN file_size ELSE 0 END) as today_download,
        COUNT(CASE WHEN type = 'upload' AND status = 'completed' THEN 1 END) as upload_count,
        COUNT(CASE WHEN type = 'download' AND status = 'completed' THEN 1 END) as download_count
       FROM transfer_tasks
       WHERE DATE(updated_at) = CURDATE() AND status = 'completed'`
    );

    // 活动传输任务数
    const [activeTasksResult] = await db.query(
      'SELECT COUNT(*) as count FROM transfer_tasks WHERE status IN ("pending", "transferring")'
    );

    // CPU和内存信息
    const cpuData = await si.currentLoad();
    const memData = await si.mem();
    const diskData = await si.fsSize();

    // 网络速度（从Redis获取，如果Redis不可用则返回0）
    let uploadSpeed = 0;
    let downloadSpeed = 0;
    try {
      if (redisClient.isOpen) {
        uploadSpeed = await redisClient.get('network:upload_speed') || 0;
        downloadSpeed = await redisClient.get('network:download_speed') || 0;
      }
    } catch (error) {
      logger.warn('从Redis获取网络速度失败，使用默认值0', error.message);
    }

    // 获取FTP服务器状态
    const ftpStatus = ftpServer.getStatus();

    res.json({
      success: true,
      data: {
        files: {
          totalSize: fileSizeResult[0].total_size || 0,
          totalCount: fileSizeResult[0].total_files || 0
        },
        users: {
          onlineCount: onlineUsersResult[0].count
        },
        today: {
          uploadSize: todayStats[0].today_upload || 0,
          downloadSize: todayStats[0].today_download || 0,
          uploadCount: todayStats[0].upload_count || 0,
          downloadCount: todayStats[0].download_count || 0
        },
        activeTasks: activeTasksResult[0].count,
        ftp: {
          isRunning: ftpStatus.isRunning,
          activeConnections: ftpStatus.activeConnections,
          activeTransfers: ftpStatus.activeTransfers
        },
        system: {
          cpu: {
            usage: cpuData.currentLoad.toFixed(2),
            cores: cpuData.cpus.length
          },
          memory: {
            total: memData.total,
            used: memData.used,
            usage: ((memData.used / memData.total) * 100).toFixed(2)
          },
          disk: diskData.map(disk => ({
            fs: disk.fs,
            size: disk.size,
            used: disk.used,
            usage: disk.use.toFixed(2)
          })),
          network: {
            uploadSpeed: parseInt(uploadSpeed),
            downloadSpeed: parseInt(downloadSpeed)
          }
        }
      }
    });
  } catch (error) {
    logger.error('获取系统概览失败:', error);
    res.status(500).json({
      success: false,
      message: '获取系统概览失败'
    });
  }
};

/**
 * 获取网络流量趋势
 */
exports.getNetworkTrend = async (req, res) => {
  try {
    const { days = 7 } = req.query;

    // 从transfer_tasks实时计算统计数据
    const [stats] = await db.query(
      `SELECT
        DATE(updated_at) as stat_date,
        SUM(CASE WHEN type = 'upload' THEN file_size ELSE 0 END) as upload,
        SUM(CASE WHEN type = 'download' THEN file_size ELSE 0 END) as download
       FROM transfer_tasks
       WHERE status = 'completed'
         AND updated_at >= DATE_SUB(CURDATE(), INTERVAL ? DAY)
         AND updated_at IS NOT NULL
       GROUP BY DATE(updated_at)
       ORDER BY stat_date ASC`,
      [days]
    );

    // 填充缺失的日期（用0填充）
    const result = [];
    const today = new Date();
    for (let i = days - 1; i >= 0; i--) {
      const date = new Date(today);
      date.setDate(date.getDate() - i);
      const dateStr = date.toISOString().split('T')[0];

      const found = stats.find(s => s.stat_date && s.stat_date.toISOString().split('T')[0] === dateStr);
      result.push({
        stat_date: dateStr,
        upload: found ? found.upload : 0,
        download: found ? found.download : 0
      });
    }

    res.json({
      success: true,
      data: result
    });
  } catch (error) {
    logger.error('获取网络流量趋势失败:', error);
    res.status(500).json({
      success: false,
      message: '获取网络流量趋势失败'
    });
  }
};

/**
 * 获取地域流量分布
 */
exports.getLocationStats = async (req, res) => {
  try {
    const [stats] = await db.query(
      `SELECT
        province,
        city,
        SUM(upload_bytes + download_bytes) as total_bytes,
        SUM(access_count) as access_count,
        latitude,
        longitude
       FROM ip_stats
       WHERE province IS NOT NULL
       GROUP BY province, city, latitude, longitude
       ORDER BY total_bytes DESC
       LIMIT 100`
    );

    // 如果没有数据，返回空数组（而不是报错）
    res.json({
      success: true,
      data: stats || []
    });
  } catch (error) {
    logger.error('获取地域流量分布失败:', error);
    // 即使出错也返回空数组，避免前端报错
    res.json({
      success: true,
      data: []
    });
  }
};

/**
 * 获取用户排行
 */
exports.getUserRanking = async (req, res) => {
  try {
    const { type = 'upload', limit = 10 } = req.query;

    let orderBy = 'total_uploaded';
    if (type === 'download') {
      orderBy = 'total_downloaded';
    } else if (type === 'total') {
      orderBy = '(total_uploaded + total_downloaded)';
    }

    const [users] = await db.query(
      `SELECT * FROM v_user_transfer_stats
       ORDER BY ${orderBy} DESC
       LIMIT ?`,
      [parseInt(limit)]
    );

    res.json({
      success: true,
      data: users
    });
  } catch (error) {
    logger.error('获取用户排行失败:', error);
    res.status(500).json({
      success: false,
      message: '获取用户排行失败'
    });
  }
};

/**
 * 获取传输任务统计
 */
exports.getTransferStats = async (req, res) => {
  try {
    const [stats] = await db.query(
      `SELECT
        status,
        COUNT(*) as count,
        SUM(file_size) as total_size
       FROM transfer_tasks
       GROUP BY status`
    );

    res.json({
      success: true,
      data: stats
    });
  } catch (error) {
    logger.error('获取传输任务统计失败:', error);
    res.status(500).json({
      success: false,
      message: '获取传输任务统计失败'
    });
  }
};

/**
 * 获取文件类型分布
 */
exports.getFileTypeStats = async (req, res) => {
  try {
    const [stats] = await db.query(
      `SELECT
        CASE
          WHEN mime_type LIKE 'image/%' THEN '图片'
          WHEN mime_type LIKE 'video/%' THEN '视频'
          WHEN mime_type LIKE 'audio/%' THEN '音频'
          WHEN mime_type LIKE 'text/%' THEN '文本'
          WHEN mime_type LIKE 'application/pdf' THEN 'PDF'
          WHEN mime_type LIKE 'application/%zip%' OR mime_type LIKE 'application/%rar%' THEN '压缩包'
          ELSE '其他'
        END as type,
        COUNT(*) as count,
        SUM(file_size) as total_size
       FROM files
       WHERE is_deleted = 0 AND is_directory = 0
       GROUP BY type
       ORDER BY count DESC`
    );

    res.json({
      success: true,
      data: stats
    });
  } catch (error) {
    logger.error('获取文件类型分布失败:', error);
    res.status(500).json({
      success: false,
      message: '获取文件类型分布失败'
    });
  }
};

/**
 * 获取小时级流量统计
 */
exports.getHourlyStats = async (req, res) => {
  try {
    const [stats] = await db.query(
      `SELECT
        stat_hour,
        AVG(total_upload) as avg_upload,
        AVG(total_download) as avg_download
       FROM system_stats
       WHERE stat_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
       AND stat_hour IS NOT NULL
       GROUP BY stat_hour
       ORDER BY stat_hour ASC`
    );

    res.json({
      success: true,
      data: stats
    });
  } catch (error) {
    logger.error('获取小时级流量统计失败:', error);
    res.status(500).json({
      success: false,
      message: '获取小时级流量统计失败'
    });
  }
};

/**
 * 获取FTP服务器状态
 */
exports.getFTPStatus = async (req, res) => {
  try {
    const status = ftpServer.getStatus();
    const connections = ftpServer.getActiveConnections();

    res.json({
      success: true,
      data: {
        ...status,
        connections
      }
    });
  } catch (error) {
    logger.error('获取FTP状态失败:', error);
    res.status(500).json({
      success: false,
      message: '获取FTP状态失败'
    });
  }
};

/**
 * 获取FTP活动连接列表
 */
exports.getFTPConnections = async (req, res) => {
  try {
    const connections = ftpServer.getActiveConnections();

    res.json({
      success: true,
      data: connections
    });
  } catch (error) {
    logger.error('获取FTP连接列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取FTP连接列表失败'
    });
  }
};
